package com.mattgarner.jaddas.node.command.dml;

import com.mattgarner.jaddas.dataset.DataSet;
import com.mattgarner.jaddas.node.DataSetManager;
import com.mattgarner.jaddas.node.RemoteClient;
import com.mattgarner.jaddas.node.command.CommandParser;
import com.mattgarner.jaddas.node.data.LocalTableDataProvider;
import com.mattgarner.jaddas.node.data.TableException;
import com.mattgarner.jaddas.node.data.TableHeader;
import com.mattgarner.jaddas.node.net.Protocol;
import com.mattgarner.jaddas.node.net.Worker;

public class CmdInsertInto extends CommandParser {

	public CmdInsertInto(Worker serverWorker, RemoteClient client) {
		super(serverWorker, client);
	}
	
	// INSERT INTO DATASET
	public final boolean parseCommand(String command) {
		Worker worker = getServerWorker();
		RemoteClient clientConfig = getRemoteClient();
		
		String[] cmd = extractRegexGroups("(?i)^INSERT\\s+INTO\\s+([A-Z0-9_\\.]+?)\\s+VALUES\\s*\\((.*?)\\)$", command);
		String dsName = cmd[0];
		String insertValueSet = cmd[1];
		
		DataSetManager dsManager = DataSetManager.getInstance();
		DataSet dataSet = dsManager.getDataSetByName(dsName);
		
		if(dataSet == null) {
			worker.sendMessage(Protocol.MSG_NAK, "DataSet '"+dsName+"' was not found.");
			return true;
		}
		
		TableHeader dataTableHeader = dataSet.getDataTableHeader();
		String[] insertValues = insertValueSet.split("\\s*,\\s*");

		int tableDataColumnCount = 0;
		
		try {
			tableDataColumnCount = dataTableHeader.getColumnCount(); 
		} catch(TableException e) {
			worker.sendMessage(Protocol.MSG_NAK, "TableException: " + e.getMessage());
			return true;
		}
		if(insertValues.length != tableDataColumnCount) {
			worker.sendMessage(Protocol.MSG_NAK, "Column count mismatch. Supplied "+insertValues.length+", expected "+tableDataColumnCount+".");
			return true;
		}
		
		//ResultSetHeader rsInputHeader = new ResultSetHeader(LocalTable.STRING_ENCODING);
		//ResultSet rsInputData = new ResultSet(rsInputHeader);
		LocalTableDataProvider dsDataProvider = null;
		try { 
			dsDataProvider = new LocalTableDataProvider(dataSet);
			
			String[] columns = new String[dataTableHeader.getColumnCount()];
			String[] values = new String[dataTableHeader.getColumnCount()];
			
			// order data for insert
			for(int b=0; b<dataTableHeader.getColumnCount(); b++) {
				columns[b] = dataTableHeader.getColumnName(b);
				values[b] = insertValues[b].replaceAll("^'", "").replaceAll("'$", "");
			}
			
			dsDataProvider.updateIntoDataSet(columns, values);
			
		} catch(Exception e) {
			worker.sendMessage(Protocol.MSG_NAK, "DataSetException: " + e.getMessage());
			return true;
		}
		
		worker.sendMessage(Protocol.MSG_OK, "Inserted 1 row(s) into '"+dsName+"'. (in "+calculateExecuteTime()+" secs.)");
		return true;

	}

}
